package _18_剑指OfferII;

import java.util.Arrays;

public class _003_剑指OfferII前n个数字二进制中1的个数 {

    public static void main(String[] args) {
        _003_剑指OfferII前n个数字二进制中1的个数 v = new _003_剑指OfferII前n个数字二进制中1的个数();

        System.out.println(Arrays.toString(v.countBits(5)));
    }

    // 截取低位，获取
    public int[] countBits(int n) {
        int[] results = new int[n + 1];
        for (int i = 1; i < results.length; i++) {
            results[i] = 1 + results[i & (i - 1)];
        }
        return results;
    }

    public int[] countBits1(int n) {
        int[] results = new int[n + 1];
        for (int i = 0; i < results.length; i++) {
            results[i] = countBit(i);
        }
        return results;
    }

    // 统计二进制有多少位, n & (n - 1) 消除低位1，获得原有数据
    private int countBit(int n) {
        int count = 0;
        while (n != 0) {
            n &= n - 1;
            count++;
        }
        return count;
    }

}
